package cn.iocoder.yudao.module.pickbook.service.auth;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.biz.system.oauth2.OAuth2TokenCommonApi;
import cn.iocoder.yudao.framework.common.biz.system.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import cn.iocoder.yudao.framework.common.biz.system.oauth2.dto.OAuth2AccessTokenRespDTO;
import cn.iocoder.yudao.module.pickbook.controller.app.auth.vo.PickbookAuthLoginRespVO;
import cn.iocoder.yudao.module.pickbook.controller.app.auth.vo.PickbookAuthWeixinLoginReqVO;
import cn.iocoder.yudao.module.pickbook.dal.dataobject.user.PickbookUserDO;
import cn.iocoder.yudao.module.pickbook.service.user.PickbookUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 绘本用户认证 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Slf4j
public class PickbookAuthServiceImpl implements PickbookAuthService {

    @Resource
    private PickbookUserService userService;
    @Resource
    private OAuth2TokenCommonApi oauth2TokenApi;

    @Override
    @Transactional
    public PickbookAuthLoginRespVO weixinLogin(PickbookAuthWeixinLoginReqVO reqVO) {
        // 1. 模拟微信登录，获取用户信息
        // 注意：这里需要集成真实的微信API，目前使用模拟数据
        String openid = generateMockOpenid(reqVO.getCode());
        String unionid = generateMockUnionid(reqVO.getCode());
        
        // 2. 获取或创建用户
        PickbookUserDO user = userService.getUserByOpenid(openid);
        if (user == null) {
            // 创建新用户
            user = userService.createUser(openid, unionid, reqVO.getNickname(), reqVO.getAvatar());
        } else {
            // 更新用户信息
            if (StrUtil.isNotEmpty(reqVO.getNickname())) {
                user.setNickname(reqVO.getNickname());
            }
            if (StrUtil.isNotEmpty(reqVO.getAvatar())) {
                user.setAvatar(reqVO.getAvatar());
            }
            userService.updateUser(user);
        }

        // 3. 创建访问令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(
                new OAuth2AccessTokenCreateReqDTO()
                        .setUserId(user.getId())
                        .setUserType(UserTypeEnum.PICKBOOK.getValue())
                        .setClientId("default"));

        // 4. 构建返回结果
        return PickbookAuthLoginRespVO.builder()
                .userId(user.getId())
                .accessToken(accessTokenRespDTO.getAccessToken())
                .refreshToken(accessTokenRespDTO.getRefreshToken())
                .expiresTime(accessTokenRespDTO.getExpiresTime())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .role(user.getRole())
                .openid(user.getOpenid())
                .build();
    }

    @Override
    public void logout(String token) {
        // 删除访问令牌
        oauth2TokenApi.removeAccessToken(token);
    }

    /**
     * 模拟生成OpenID
     * 实际项目中需要调用微信API获取真实的OpenID
     */
    private String generateMockOpenid(String code) {
        // 这里应该调用微信API获取真实的OpenID
        // 目前使用code作为基础生成模拟的OpenID
        return "mock_openid_" + code.hashCode();
    }

    /**
     * 模拟生成UnionID
     * 实际项目中需要调用微信API获取真实的UnionID
     */
    private String generateMockUnionid(String code) {
        // 这里应该调用微信API获取真实的UnionID
        // 目前使用code作为基础生成模拟的UnionID
        return "mock_unionid_" + code.hashCode();
    }

} 